#include "tcpsocket.h"


TcpSocket::TcpSocket(QString &ip, quint16 port)
{
    m_tcp = new QTcpSocket();
    m_tcp->connectToHost(ip, port, QTcpSocket::ReadWrite);
}

void TcpSocket::sendData(QString data)
{
    // 数据做base64转码
    QByteArray base64 = data.toUtf8().toBase64();
    QString le;
    // 预留8字节保存长度
    le.sprintf("%08d", base64.size());
    // 拼接数据 报文长度+报文
    base64 = le.toUtf8() + base64;
    // 发送数据
    m_tcp->write(base64.data(), base64.size());

}

QByteArray TcpSocket::readData()
{
    char buf[9]={0};
    // 每次取8个字节长度
    m_tcp->read(buf, 8);
    int len = atoi(buf);
    // 保存数据缓冲区
    char data[len+1] = {0};
    // 读取指定长度
    m_tcp->read(data, len);
    // base64转码
    QByteArray row = QByteArray::fromBase64(data);
    return row;
}


TcpSocket::~TcpSocket()
{
    delete m_tcp;
}

